const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const formatYMD = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${[year, month, day].map(formatNumber).join('-')}`
}

/**
 * 防抖函数
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} isImmediate
 */
/*const debounce = (func, wait, isImmediate) => {
  let timeout, fnargs, context, timestamp, result
  const later = function() {
    // 距上一次触发时间间隔
    const last = +new Date() - timestamp
    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if(last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为isImmediate===true，因为开始边界已经调用过了此处无需调用
      if(!isImmediate) {
        result = func.apply(context, fnargs)
        if (!timeout) context = fnargs = null
      }
    }
  }
  return function(...args) {
    context = this
    timestamp = +new Date()
    fnargs = args
    const callNow = isImmediate && !timeout
    // 如果延时不存在，重新设定延时
    if(!timeout) timeout = setTimeout(later, wait)
    if(callNow) {
      result = func.apply(context, fnargs)
      context = fnargs = null
    }
    return result
  }
}*/
const debounce = (func, wait, isImmediate) =>{
  var timeout;
  return function () {
    var context = this, args = arguments;
    var later = function () {
      timeout = null;
      if (!isImmediate) func.apply(context, args);
    };
    var callNow = isImmediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

/**
 * 节流函数
 * @param {Function} func
 * @param {number} wait 延迟时间
 * @param mustRun 触发时间间隔
 * @return {Function}
 */
const throttle = (func, wait, mustRun) =>{
  var timeout,
    startTime = new Date();

  return function() {
    var context = this,
      args = arguments,
      curTime = new Date();

    clearTimeout(timeout);
    // 如果达到了规定的触发时间间隔，触发 handler
    if(curTime - startTime >= mustRun){
      func.apply(context,args);
      startTime = curTime;
      // 没达到触发间隔，重新设定定时器
    }else{
      timeout = setTimeout(func, wait);
    }
  };
}

// 登录信息 cookie 设置
const setLoginStorage = (data) => {
  let { refresh_token, token, company_name, company_id, system_id, user_name, user_id, role_id,role_name, is_platfrom, is_agent, client_type, employee_row_id, is_all_zt,zt_id,zt_name,is_zt,department_id,department_name,
    driver_row_id, driver_id, gs_name, driver_name, driver_car_row_id, driver_car_id, driver_car_name
  } = data
  let level = client_type === 'platform' ? '1' : client_type === 'agent_level_1' ? '2' : client_type === 'agent_level_2' ? '3' : '4'

  //231123 yan 增加储存登录司机信息
  let storageObj = {
    refresh: refresh_token,
    token: token,
    company_name,
    company_id,
    system_id,
    user_name,
    user_id,
    role_id,
    role_name,
    is_platfrom,
    is_agent,
    userLevel: level,
    gs_name,
    employee_row_id,
    is_all_zt,
    zt_id,
    zt_name,
    is_zt,
    department_id,
    department_name,
    driver_row_id,driver_id,driver_name,driver_car_row_id,driver_car_id,driver_car_name
  }

  Object.entries(storageObj).forEach(([key, val]) => wx.setStorageSync(key, val))
}

// 格式化数字
function formatNum(num, type) {
  let newNum = 0
  if(type === 1) {  // 转普通数字
    newNum = parseFloat(num.replace(/[^\d\\.-]/g, '')) || 0
  } else {  // 转金额数字
    newNum = Number(Number(num).toFixed(2)).toLocaleString('zh', { minimumFractionDigits: 2 })
  }
  return newNum
}

/**
 * 格式化日期时间
 * @param {Date} date
 * @param {string} fmt
 */
const formatDate = (date, fmt) => {
  if(!fmt) fmt = 'yyyy-MM-dd HH:mm:ss'
  const o = {
    'M+': date.getMonth() + 1,      // 月份
    'd+': date.getDate(),           // 日
    'H+': date.getHours(),          // 小时
    'm+': date.getMinutes(),        // 分钟
    's+': date.getSeconds(),        // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3),  // 季度
    'S': date.getMilliseconds(),    // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, o[k].toString().length === 1 ? '0' + o[k] : o[k])
    }
  }
  return fmt
}

/**
 * 获取某个月第一天
 * @param {number|string} year
 * @param {number|string} month 1-12
 */
const getMonthFirstDate = (year, month) => {
  if(year === undefined || month === undefined) {
    let today = new Date()
    year = today.getFullYear()
    month = today.getMonth() + 1
  }
  return new Date(year, month - 1, 1)
}

/**
 * 获取某个月最后一天
 * @param {number|string} year
 * @param {number|string} month 1-12
 */
const getMonthLastDate = (year, month) => {
  if(year === undefined || month === undefined) {
    let today = new Date()
    year = today.getFullYear()
    month = today.getMonth() + 1
  }
  return new Date(year, month, 0)
}

/**
 * 获取本周、上周、下周的起始、结束日期
 * @param {string} type 开始日期/结束日期 's'/'e'
 * @param {number} dates 不传或0：本周/ -1：上周 / 1：下周
 */
const getWeekFirstLastDate = (type, dates)=>{
  let now = new Date(),
    nowTime = now.getTime(),
    day = now.getDay(),
    longtime = 24 * 60 * 60 * 1000,
    n = longtime * 7 * (dates || 0),
    dd = '';
  if (type === 's'){
    dd = nowTime - (day - 1) * longtime + n;
  }
  if (type === 'e'){
    dd = nowTime + (7 - day) * longtime + n;
  }
  dd = new Date(dd);
  let y = dd.getFullYear(),
    m = dd.getMonth() + 1,
    d = dd.getDate();
  m = m < 10 ? "0" + m: m;
  d = d < 10 ? "0" + d: d;
  return y + "-" + m + "-" + d;
};


/**
 * 小程序选择的图片临时本地路径转为base64
 * @param {string} url
 * @param {string} type
 */
const base64 = (url, type = 'png') => {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().readFile({
      filePath: url,        // 选择图片返回的相对路径
      encoding: 'base64',   // 编码格式
      success(res) {
        resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
      },
      fail(res) {
        reject(res.errMsg)
      },
    })
  })
}

/**
 * 格式化日期时间
 * @param {string} value
 * @param {string} fmt
 */
const crtTimeFtt = (value, fmt) => {
  // fmt = fmt || 'yyyy-MM-dd HH:mm:ss'
  fmt = fmt || 'yyyy-MM-dd'
  if(value && typeof value === 'string') {
    value = value.replace(/-/g, '/')
    let date = new Date(value)
    return formatDate(date, fmt)
  } else {
    return value || ''
  }
}


export const GetUrlString = (url,name) =>{
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  var query = url.split('?')[1];
  var r = query && url.split('?')[1].match(reg);
  if(r!=null)return unescape(decodeURI(r[2])); return null;
}


// module.exports = {
//   formatTime
// }
wx.$util = {
  formatTime,
  formatNumber,
  debounce,
  throttle,
  setLoginStorage,
  formatNum,
  formatDate,
  getMonthFirstDate,
  getMonthLastDate,
  base64,
  crtTimeFtt,
  getWeekFirstLastDate,
  GetUrlString,
  formatYMD
}
